package com.easy.service.impl;

import com.auth0.jwt.JWT;
import com.easy.bean.User;
import com.easy.dao.IUserDao;
import com.easy.service.IUserService;
import com.easy.utils.DigestUtil;
import com.easy.utils.JWTUtil;
import com.easy.utils.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    IUserDao dao;

    DigestUtil digestUtil;

    private boolean eqPassword(String password, String password_data){
        return password.equals(password_data);
    }

    @Override
    public String doLogin(User user) {
        //1.获取数据库中的数据 byname
        List<User> list = dao.getUserByPhoneNumber(user);
        if(list.size()==1){
            User user_data = list.get(0);
            boolean bool = digestUtil.decode(user.getPassword(),user_data.getPassword());
            //2.比较密码
            if(bool){
                HashMap<String, Object> map = new HashMap();
                map.put("id", user_data.getId());
                map.put("username", user_data.getUsername());
                map.put("password",user_data.getPassword());
                map.put("phoneNumber",user_data.getPhoneNumber());
                map.put("imgUrl",user_data.getImgUrl());
                //3.生成token
                return JWTUtil.createToken(map);
            }
        }
        return null;
    }

    @Override
    public Map<String, Object> decode(String token) {
        Map<String, Object> userInfo = JWT.decode(token).getClaim("userInfo").asMap();
        return userInfo;
    }

    @Override
    public User getUserByID(int id) {
        return dao.getUserByID(id);
    }

    @Override
    public List<User> getUserByPhoneNumber(User user) {
        return dao.getUserByPhoneNumber(user);
    }

    @Override
    public List<User> getUser(User user, Page page) {
        return dao.getUser(user,page);
    }

    @Override
    public int getUserCount(User user) {
        return dao.getUserCount(user);
    }

    @Override
    public int delUser(int id) {
        return dao.delUser(id);
    }

    @Override
    public int addUser(User user) {
        return dao.addUser(user);
    }

    @Override
    public int editUser(User user) {
        return dao.editUser(user);
    }

}
